﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Tron.Helpers;
using Tron.DataStructures;

namespace Tron.Players.Simple
{
    /// <summary>
    /// This player chooses a random direction from the directions that will result in the maximum
    /// number of possible choices next move.
    /// </summary>
    class OpenSpacePlayer : Player
    {
        public OpenSpacePlayer(int playerIndex)
            : base(playerIndex) { }

        public override void Update(Percepts percepts, Actions actions)
        {
            IPlayerStatePercepts playerState = percepts.PlayerStates[PlayerIndex];

            List<Vector2> possibleDirections = SimplePlayerHelper.PossibleDirectionsFromPosition(percepts, playerState.Position);
            if (possibleDirections.Count > 0)
            {
                List<int> availableDirectionsNextMove = new List<int>();
                foreach (Vector2 possibleDirection in possibleDirections)
                {
                    Vector2 possibleNextPosition = playerState.Position + possibleDirection;
                    availableDirectionsNextMove.Add(SimplePlayerHelper.PossibleDirectionsFromPosition(percepts, possibleNextPosition).Count);
                }
                int maxAvailableDirectionsNextMove = availableDirectionsNextMove.Max();

                for (int i = 0; i < possibleDirections.Count; i++)
                {
                    if (availableDirectionsNextMove[i] < maxAvailableDirectionsNextMove)
                    {
                        possibleDirections.RemoveAt(i);
                        availableDirectionsNextMove.RemoveAt(i);
                    }
                }

                int randomIndex = RandomAid.NextIntInRange(0, possibleDirections.Count - 1);
                actions.MoveDirection = possibleDirections[randomIndex];
            }
        }
    }
}
